package controller.admin;

import model.Page;
import model.Type;
import service.GoodsService;
import service.TypeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * 商品管理展示
 */
@WebServlet(name = "AdminGoodsListServlet", value = "/admin/goods_list")
public class AdminGoodsListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GoodsService gs = new GoodsService();
        //初始化默认值
        int type = 0;
        int pageNumber = 1;
        Page page = null;

        //获取参数
        String tempPageNumber = request.getParameter("pageNumber");
        String tempType = request.getParameter("type");

        //如果传了就赋值
        if (tempPageNumber != null && !"".equals(tempPageNumber)) {
            //防止页码小于1
            pageNumber = Integer.parseInt(tempPageNumber) <= 0 ? 1 : Integer.parseInt(tempPageNumber);
        }
        //如果传了就赋值
        if (tempType != null && !"".equals(tempType)) {
            type = Math.max(Integer.parseInt(tempType), 0);
        }

        try {
            //获取指定页码的商品数据
            page = gs.selectPageByType(type, pageNumber);
            request.getSession().setAttribute("p", page);
            request.setAttribute("type", type);
            List<Type> typeList = new TypeService().getTypeList();
            request.getSession().setAttribute("typeList", typeList);
            request.getRequestDispatcher("goods_list.jsp").forward(request, response);
        } catch (SQLException e) {
            request.getRequestDispatcher("goods_list.jsp").forward(request, response);
            e.printStackTrace();
        }

    }
}
